import { CaseApi } from "@/api";
import { useCallback, useState } from "react";

/** 测试hook 中  */

type A<T extends (params: any) => any> = T extends (
  params: any
) => Promise<infer U>
  ? U
  : ReturnType<T>;

export function useHandleData<T extends (...params: any[]) => any>(
  api: T,
  handleSuccess: (params: A<T>) => void,
  handleFail?: (params: A<T>) => void
) {
  const [loading, setLoading] = useState(false);

  const getData = useCallback(async (...params: Parameters<T>) => {
    setLoading(true);
    try {
      const res: A<T> = await api(...params);
      setLoading(false);
      handleSuccess(res);
      return res;
    } catch (error: any) {
      setLoading(false);
      handleFail?.(error);
      return Promise.reject(error);
    }
  }, []);

  return [getData, loading] as const;
}

// const [getData, dataLoading] = useHandleData(
//   CaseApi.fetchPosition,
//   (data) => {}
// );
// useEffect(() => {
//   getData({ name: "1123" });
// }, []);
/**
 * @desc 业务处理逻辑
 *
 */
export function useFetchData<
  T extends (...params: any[]) => Promise<any>,
  P extends A<T> | undefined
>(api: T, defaultValue?: P) {
  const [data, setData] = useState<A<T> | undefined>(defaultValue);
  const [loading, setLoading] = useState(false);

  /** 返回正常的Promise 即可 */
  const getData = async (...params: Parameters<T>) => {
    setLoading(true);

    try {
      const data: A<T> = await api(...params);
      setData(data);
      return data;
    } catch (error) {
      return Promise.reject(error);
    }
  };

  return [
    data as P extends undefined ? A<T> | undefined : A<T>,
    getData,
    loading,
  ] as const;
}

// type CC<T> = T extends (params: any) => infer U | Promise<infer U> ? U : never;

// export function useFetch<T extends (...params: any[]) => any, U>(
//   api: T,
//   initData?: CC<T>
// ) {
//   const [data, setData] = useState<CC<T> | undefined>(initData);

//   const getData = async (...params: Parameters<T>) => {
//     try {
//       const res: CC<T> = await api(...params);
//       setData(res);
//       return res;
//     } catch (error) {
//       return Promise.reject(error);
//     }
//   };

//   return [
//     data as U extends undefined ? undefined | CC<T> : CC<T>,
//     getData,
//   ] as const;
// }

// const [data, getData] = useFetch(CaseApi.fetchPosition, {
//   id: 1,
//   name: "test",
//   staff_count: 0,
//   create_time: "2022-04-11 13:59:21",
// });

// useEffect(() => {
//   getData({ name: "1123" });
// }, []);
